import Dijkstra from "ol-ext/geom/Dijkstra";
import Placemark from "ol-ext/overlay/Placemark";
import { unByKey } from "ol/Observable";
import { makeHighlight } from "./highlightlib";
import routeLayer from "./layers/routeLayer";
import { getMainMap } from "./MainMap";

function makeFunctionsInvoker(functions) {
  return () => {
    for (const f of functions) {
      f();
    }
  };
}

function makeHighlightForFeatures(features) {
  let [onVector, offVector] = [[], []];
  for (const feature of features) {
    const [on, off] = makeHighlight(feature);
    onVector.push(on);
    offVector.push(off);
  }
  return [makeFunctionsInvoker(onVector), makeFunctionsInvoker(offVector)];
}

let dehighlightFunction = undefined;

function highlightFeatures(features) {
  let [on, off] = makeHighlightForFeatures(features);
  on();
  dehighlightFunction = off;
}

function dehighlightFeatures() {
  if (dehighlightFunction !== undefined) {
    startMark.hide();
    finishMark.hide();
    dehighlightFunction();
    dehighlightFunction = undefined;
  }
}

let clickKey = undefined;
let startMark = undefined;
let finishMark = undefined;
let startPosition = undefined;

export function beginDijkstra() {
  if (clickKey === undefined) {
    const dijkstra = new Dijkstra({ source: routeLayer.getSource() });
    dijkstra.on("start", (e) => dehighlightFeatures());
    dijkstra.on("finish", (e) => {
      highlightFeatures(e.route);
      setTimeout(dehighlightFeatures, 1000);
    });
    startMark = new Placemark({ popupClass: "flagv", color: "#080" });
    finishMark = new Placemark({ popupClass: "flag finish", color: "#000" });
    const map = getMainMap();
    map.addOverlay(startMark);
    map.addOverlay(finishMark);
    clickKey = map.on("click", (e) => {
      if (startPosition === undefined) {
        startPosition = e.coordinate;
        startMark.show(startPosition);
        finishMark.hide();
      } else {
        const result = dijkstra.path(startPosition, e.coordinate);
        if (result) {
          finishMark.show(result[1]);
          startPosition = undefined;
        }
      }
    });
  }
}

export function endDijkstra() {
  dehighlightFeatures();
  if (clickKey !== undefined) {
    startMark.hide();
    finishMark.hide();
    const map = getMainMap();
    map.removeOverlay(startMark);
    map.removeOverlay(finishMark);
    unByKey(clickKey);
    clickKey = undefined;
    startMark = undefined;
    finishMark = undefined;
    startPosition = undefined;
  }
}

// export function initializeDijkstra() {
//   const map = getMainMap();
//   map.addOverlay(popStart);
//   map.addOverlay(popEnd);
//   map.on("click", function (e) {
//     if (!start) {
//       start = e.coordinate;
//       popStart.show(start);
//     } else {
//       var se = dijkstra.path(start, e.coordinate);
//       if (se) {
//         start = se[0];
//         end = se[1];
//         popEnd.show(end);
//       }
//     }
//   });
// }
